package com.other.src.main.java.com.kuang.cas;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicStampedReference;

public class CASDemo {
    public static void main(String[] args) {
//
//        AtomicInteger atomicInteger = new AtomicInteger(2020);

        // Integer 对象缓存机制，产生新对象。 这是一个大坑 valueOf使用缓存。默认范围时-128 ～ 127 超过就会产生新对象。
        AtomicStampedReference<Integer> atomicInteger = new AtomicStampedReference<>(1, 1);

        new Thread(()->{
            int stamp = atomicInteger.getStamp();

            System.out.println("a1->"+stamp);

            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            // version +1

            System.out.println("a2修改"+atomicInteger.compareAndSet(1, 2, atomicInteger.getStamp(), atomicInteger.getStamp() + 1));

            System.out.println("a2->"+atomicInteger.getStamp());


            System.out.println("a3修改"+atomicInteger.compareAndSet(2, 1, atomicInteger.getStamp(), atomicInteger.getStamp() + 1));
            System.out.println("a3->"+atomicInteger.getStamp());

        },"A").start();
        new Thread(()->{
            int stamp = atomicInteger.getStamp();
            System.out.println("b1->"+stamp);
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("b2修改"+atomicInteger.compareAndSet(1, 6, stamp, stamp + 1));
            System.out.println("b2->"+atomicInteger.getStamp());

        },"B").start();
    }
}
